package com.yj.springbootinsert_multiple_data.service;

import com.yj.springbootinsert_multiple_data.entity.Info;
import com.yj.springbootinsert_multiple_data.mapper.InfoDao;
import com.yj.springbootinsert_multiple_data.mapper.InfoExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class InfoService {




    @Autowired
    InfoDao infoDao;

    private static List<Info> list;

    static {
        list = new ArrayList<>(10);
        for (int i = 0; i < 2000000; i++) {
            list.add(new Info().setId(i).setName("nihao"+i).setPhone("123456aaa"+i));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void insert_batch(){
        long startTime = System.currentTimeMillis();
//        log.info("list:{}",list);
//        infoDao.insertBatch(list);

        int nThreadSize = 50;

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(nThreadSize, 100, 2000, TimeUnit.SECONDS, new ArrayBlockingQueue<>(50), new ThreadPoolExecutor.DiscardPolicy());

        int listSize = list.size();
        // nThreadSize = 5  list = 20
        for (int i = 0; i < nThreadSize; i++) {
            // 0 4 2
            List<Info> infos = list.subList(listSize / nThreadSize * i , listSize / nThreadSize * (i +1));
            log.info("infos:{}",infos);
            threadPoolExecutor.execute(()->{
                infoDao.insertBatch(infos);
            });

        }


        long endTime = System.currentTimeMillis();


        log.info("finishTime:{} ms",(endTime-startTime));

    }


}
